<template>
  <admin-layout>
    <div class="orders-view">
      <h2 class="page-title">订单管理</h2>

      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="订单号">
            <el-input
              v-model="searchForm.orderNo"
              placeholder="请输入订单号"
              clearable
            />
          </el-form-item>

          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>

          <el-form-item label="商家名称">
            <el-input
              v-model="searchForm.storeName"
              placeholder="请输入商家名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="订单状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 订单列表 -->
      <el-card class="table-card" v-loading="loading">
        <el-table :data="orderList" border style="width: 100%" row-key="id">
          <el-table-column prop="orderNo" label="订单号" min-width="180" />

          <el-table-column prop="username" label="用户名" min-width="120" />

          <el-table-column prop="storeName" label="商家名称" min-width="120" />

          <el-table-column prop="totalAmount" label="订单金额" width="100">
            <template #default="{ row }">
              ¥{{ row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>

          <el-table-column prop="status" label="订单状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="paymentMethod" label="支付方式" width="100">
            <template #default="{ row }">
              {{ getPaymentMethodLabel(row.paymentMethod) }}
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="下单时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="viewOrderDetail(row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="orderList.length === 0 && !loading" class="empty-data">
          暂无订单数据
        </div>

        <!-- 分页 -->
        <div
          class="pagination-container"
          v-if="pagination.total > 0 || pagination.currentPage > 1"
        >
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

      <!-- 订单详情对话框 -->
      <el-dialog
        v-model="detailDialog.visible"
        title="订单详情"
        width="800px"
        class="order-detail-dialog"
      >
        <div class="order-detail" v-if="detailDialog.order">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="订单号">
              {{ detailDialog.order.orderNo }}
            </el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(detailDialog.order.status)">
                {{ getStatusLabel(detailDialog.order.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="下单用户id">
              {{ detailDialog.order.userId }}
            </el-descriptions-item>
            <el-descriptions-item label="商家名称">
              {{ detailDialog.order.storeName }}
            </el-descriptions-item>
            <el-descriptions-item label="下单时间">
              {{ formatDate(detailDialog.order.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">
              {{ getPaymentMethodLabel(detailDialog.order.paymentType) }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions title="配送信息" :column="1" border class="mt-4">
            <el-descriptions-item label="收货人">
              {{ detailDialog.order.deliveryAddress.receiver }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ detailDialog.order.deliveryAddress.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="收货地址">
              {{ detailDialog.order.deliveryAddress.detailAddress }}
            </el-descriptions-item>
            <el-descriptions-item
              label="配送员"
              v-if="detailDialog.order.riderName"
            >
              {{ detailDialog.order.riderName }} ({{
                detailDialog.order.riderPhone
              }})
            </el-descriptions-item>
          </el-descriptions>

          <div class="order-items mt-4">
            <h3>订单商品</h3>
            <el-table
              :data="detailDialog.order.items"
              border
              style="width: 100%"
            >
              <el-table-column label="商品图片" width="80" align="center">
                <template #default="{ row }">
                  <el-image
                    style="width: 50px; height: 50px"
                    :src="row.foodImage"
                    :preview-src-list="[row.foodImage]"
                    fit="cover"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        {{ row.name?.substring(0, 1) }}
                      </div>
                    </template>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" min-width="120" >
                <template #default="{ row }">
                  {{ row.foodName }}
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价" width="80">
                <template #default="{ row }">
                  ¥{{ row.price.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column label="小计" width="100">
                <template #default="{ row }">
                  ¥{{ (row.price * row.quantity).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="order-summary mt-4">
            <div class="summary-item">
              <span>商品总额：</span>
              <span>¥{{ detailDialog.order.totalAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span>配送费：</span>
              <span
                >¥{{
                  detailDialog.order.deliveryFee?.toFixed(2) || "0.00"
                }}</span
              >
            </div>
            <div class="summary-item">
              <span>优惠金额：</span>
              <span
                >¥{{
                  detailDialog.order.discountAmount?.toFixed(2) || "0.00"
                }}</span
              >
            </div>
            <div class="summary-item total">
              <span>实付金额：</span>
              <span>¥{{ detailDialog.order.paymentAmount.toFixed(2) }}</span>
            </div>
          </div>

          <div class="order-remarks mt-4" v-if="detailDialog.order.remark">
            <h3>订单备注</h3>
            <p>{{ detailDialog.order.remark }}</p>
          </div>
        </div>
      </el-dialog>
    </div>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getAllOrders, getOrderDetail } from "@/api";
import AdminLayout from "@/components/admin/AdminLayout.vue";

// 定义订单类型
interface OrderItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
  image?: string;
}

interface Order {
  id: number;
  orderNo: string;
  // username: string;
  userId: number;
  storeName: string;
  storeId: number;
  totalAmount: number;
  paymentAmount: number;
  deliveryFee?: number;
  discountAmount?: number;
  status: string;
  paymentType: string;
  createdAt: string;
  paidAt?: string;
  // deliveryTime?: string;
  completedAt?: string;
  // receiverName: string;
  // receiverPhone: string;
  // receiverAddress: string;
  riderName?: string;
  riderPhone?: string;
  deliveryAddress: {
    receiver: string;
    phone: string;
    detailAddress: string;
  };
  remark?: string;
  items?: OrderItem[];
}

// 订单列表
const orderList = ref<Order[]>([]);

// 加载状态
const loading = ref(false);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 搜索参数
const searchForm = reactive({
  orderNo: "",
  username: "",
  storeName: "",
  status: "",
  timeRange: [] as string[],
});

// 状态选项
const statusOptions = [
  { value: "ORDER_CREATED", label: "已创建" },
  { value: "PENDING", label: "用户已支付" },
  { value: "MERCHANT_CONFIRMED", label: "商家已确认" },
  { value: "COOKING", label: "烹饪中" },
  { value: "READY_WAITING_RIDER", label: "待分配骑手" },
  { value: "RIDER_ASSIGNED", label: "已分配骑手" },
  { value: "FOOD_PICKED", label: "骑手已取餐" },
  { value: "DELIVERING", label: "配送中" },
  { value: "DELIVERED", label: "已送达" },
  { value: "COMPLETED", label: "已完成" },
  { value: "CANCELLED", label: "已取消" },
];

// 详情对话框
const detailDialog = reactive({
  visible: false,
  order: null as Order | null,
  loading: false,
});

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true;
  try {
    const params: {
      page: number;
      size: number;
      status?: string;
      userId?: string; // 假设可以通过username获取userId
      storeId?: string; // 假设可以通过storeName获取storeId
      // startDate?: string; // OpenAPI中没有此参数
      // endDate?: string; // OpenAPI中没有此参数
    } = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      status: searchForm.status || undefined,
      // orderNo, username, storeName, timeRange 需要后端支持或前端过滤
      // 目前根据OpenAPI文档，这些参数不在/api/admin/orders接口中
    };
    // 如果需要通过username或storeName过滤，需要先调用其他API获取对应的ID
    // 这里暂时不实现，只传递OpenAPI中明确支持的参数

    console.log("正在请求订单数据，参数:", params);
    const res = await getAllOrders(params);
    console.log("getAllOrders API响应:", res);

    const data = res.data?.data || res.data;
    console.log("解析后的数据:", data);

    if (data) {
      // 使用API文档中定义的分页格式
      orderList.value = data.content || [];

      // 确保总页数和总元素数正确设置，即使当前页为空
      if (typeof data.totalElements === "number") {
        pagination.total = data.totalElements;
      } else if (pagination.currentPage === 1 && Array.isArray(data.content)) {
        // 如果是第一页且没有提供总数，则使用当前页的长度作为总数
        pagination.total = data.content.length;
      } else if (
        pagination.currentPage > 1 &&
        Array.isArray(data.content) &&
        data.content.length === 0
      ) {
        // 如果当前页大于1且为空，保持总数不变
        // 这样可以确保用户可以返回之前的页面
      }

      console.log("成功获取订单数据:", orderList.value);
    } else {
      console.warn("API返回数据为空或格式不正确");
      orderList.value = [];

      // 如果是第一页，则将总数设为0
      if (pagination.currentPage === 1) {
        pagination.total = 0;
      }
      // 如果是其他页，保持总数不变，以便用户可以返回前面的页面
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    ElMessage.error("获取订单列表失败，请检查网络连接或API状态");
    orderList.value = [];

    // 出错时，如果是第一页，则将总数设为0
    if (pagination.currentPage === 1) {
      pagination.total = 0;
    }
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchOrders();
};

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = "";
  searchForm.username = "";
  searchForm.storeName = "";
  searchForm.status = "";
  searchForm.timeRange = [];
  pagination.currentPage = 1;
  fetchOrders();
};

// 处理页面变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchOrders();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchOrders();
};

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    ORDER_CREATED: "已创建",
    PENDING: "待支付",
    MERCHANT_CONFIRMED: "商家已确认",
    COOKING: "烹饪中",
    READY_WAITING_RIDER: "待分配骑手",
    RIDER_ASSIGNED: "已分配骑手",
    FOOD_PICKED: "骑手已取餐",
    DELIVERING: "配送中",
    DELIVERED: "已送达",
    COMPLETED: "已完成",
    CANCELLED: "已取消",
  };
  return statusMap[status] || status;
};

// 获取状态类型
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    ORDER_CREATED: "info",
    PENDING: "warning",
    MERCHANT_CONFIRMED: "success",
    COOKING: "primary",
    READY_WAITING_RIDER: "warning",
    RIDER_ASSIGNED: "primary",
    FOOD_PICKED: "primary",
    DELIVERING: "primary",
    DELIVERED: "success",
    COMPLETED: "success",
    CANCELLED: "danger",
  };
  return typeMap[status] || "info";
};

// 获取支付方式标签
const getPaymentMethodLabel = (method: string): string => {
  const methodMap: Record<string, string> = {
    ALIPAY: "支付宝",
    WECHAT: "微信支付",
    CASH: "现金支付",
    CREDIT_CARD: "信用卡",
  };
  return methodMap[method] || method;
};

// 查看订单详情
const viewOrderDetail = async (order: Order) => {
  detailDialog.loading = true;
  detailDialog.visible = true;

  try {
    const res = await getOrderDetail(order.id);
    const data = res.data?.data || res.data;

    if (data) {
      detailDialog.order = data;
    } else {
      detailDialog.order = order;
    }
  } catch (error) {
    console.error("获取订单详情失败", error);
    ElMessage.error("获取订单详情失败，请重试");
    detailDialog.order = order;
  } finally {
    detailDialog.loading = false;
  }
};

// 格式化时间
const formatDate = (dateString: string): string => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.orders-view {
  width: 100%;
}

.page-title {
  margin-bottom: 20px;
  color: var(--primary-dark);
  font-size: 1.5rem;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  min-height: 400px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.mt-4 {
  margin-top: 1rem;
}

.image-placeholder {
  width: 50px;
  height: 50px;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
}

.order-summary {
  margin-top: 1rem;
  padding: 1rem;
  background-color: var(--bg-paper);
  border-radius: 4px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}

.summary-item.total {
  font-weight: bold;
  color: #f56c6c;
  border-top: 1px solid var(--border-color);
  padding-top: 0.5rem;
  margin-top: 0.5rem;
}

.order-remarks {
  margin-top: 1rem;
  padding: 1rem;
  background-color: var(--bg-paper);
  border-radius: 4px;
}

.order-remarks h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  font-size: 1rem;
  color: var(--text-primary);
}

.order-remarks p {
  margin: 0;
  color: var(--text-secondary);
}
</style>
